package com.nb.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
@Slf4j
public class FileUploadUtil {

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.access-path}")
    private String accessPath; // This value will now be /server/images/

    /**
     * 保存图片文件
     * @param file 上传的文件
     * @param userId 用户ID，用于生成文件名的一部分，增加可读性
     * @return 存储在数据库中的相对访问路径 (e.g., /server/images/user_1_xxx.jpg)
     */
    public String saveImage(MultipartFile file, Integer userId) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        try {
            // 确保上传目录存在
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    log.error("无法创建上传目录: {}", uploadPath);
                    throw new RuntimeException("无法创建上传目录");
                }
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成唯一文件名 (用户ID + UUID)
            String uniqueFileName = "user_" + userId + "_" + UUID.randomUUID().toString() + extension;

            // 目标文件路径
            File dest = new File(uploadPath + uniqueFileName);

            // 保存文件
            file.transferTo(dest);
            log.info("文件上传成功，保存路径: {}", dest.getAbsolutePath());

            // 返回相对访问路径 (using the updated accessPath)
            String relativePath = accessPath + uniqueFileName;
            log.info("文件相对访问路径: {}", relativePath);
            return relativePath;

        } catch (IOException e) {
            log.error("文件上传失败：", e);
            throw new RuntimeException("文件上传失败");
        }
    }
}
